var x = device.width;
var y = device.height;
runtime.loadDex("./TomatoOCR/TomatoOCR.dex")
importClass('com.tomato.ocr.aj.OCRApi');
//初始化状态
let isInit = false;
let tmo_ocr =null;
function init() {
    if (isInit) {
        return;
    }
    getScreenCapture()
    tmo_ocr = new OCRApi(context, files.cwd());
    let license = "YXPJUYSPJFNZ2EM0EWJTMTHIYEMWEY5X|ZKFA5OHNLTFPSBCCLPXGKKHW";
    let flag = tmo_ocr.setLicense(license); // 设置license，见授权码获取
    tmo_ocr.setRecType("ch-3.0")
    tmo_ocr.setDetBoxType("rect")
    tmo_ocr.setDetUnclipRatio(1.9)
    tmo_ocr.setRecScoreThreshold(0.3)
    tmo_ocr.setReturnType("json")
    tmo_ocr.setBinaryThresh(0)
    // let MLKitOCR = $plugins.load("org.autojs.autojspro.plugin.mlkit.ocr");
    // ocr = new MLKitOCR();
    isInit = true;
}

//当前页面是否含有某个关键字
function hasText(t) {
    let p = false;
    try {
        if (t === undefined || t === null) {
            t = '视频'
            return p;
        }
        let img = captureScreen();
        let bitmap = img.bitmap;
        let type = 3
        let res = tmo_ocr.ocrBitmap(bitmap, type);
        for (let i = 0; i < res.length; i++) {
            let text = res[i].words
            p = res[i]
            log(res[i])
            return text;
        }
        img.recycle()
    } catch (e) {
        console.log(e)
    }
    return false;
}


//等待一个文字出现
function waitTextByOcr(t, timeout) {
    if (!timeout) {
        timeout = 5000;
    }
    let startTime = new Date().getTime();
    while (true) {
        if (new Date().getTime() - startTime > timeout) {
            log(`等待${t}超时5`);
            return false;
        }
        if (hasText(t)) {
            return true;
        } else {
            sleep(100);
        }
    }
}

//查询某个开头文本是否存在
function hasTextStart(prefix) {
    try {
        let texts = ocrText();
        for (var i = 0; i < texts.length; i++) {
            if (texts[i].words != null && texts[i].words.startsWith(prefix)) {
                return texts[i].words;
            }
        }
        return false;
    } catch (e) {
        toastLog(e)
        return false;
    }
}

//ocr识别文字
function ocrText() {
    try {
        let img = captureScreen();
        let bitmap = img.bitmap;
        let type = 3
        let res = tmo_ocr.ocrBitmap(bitmap, type);
        res = JSON.parse(res)
        // log(res);
        return res;
    } catch (e) {
        log(`识别文字错误`, e)
        return [];
    }
}

//根据ocr文字识别并点击
function clickTextByOcr(t) {
    let texts = ocrText();
    for (var i = 0; i < texts.length; i++) {
        if (texts[i].words === t) {
            click(getCenterPoint(texts[i].location).x,getCenterPoint(texts[i].location).y)
            return true;
        }
    }
    sleep(200);
    texts = ocrText();
    for (var i = 0; i < texts.length; i++) {
        if (texts[i].words === t) {
            click(getCenterPoint(texts[i].location).x,getCenterPoint(texts[i].location).y)
            return true;
        }
    }
    return false;
}

//根据ocr文字识别并点击包含的文字
function clickHasTextByOcr(t) {
    let texts = ocrText();
    for (var i = 0; i < texts.length; i++) {
        if (texts[i].words.indexOf(t) !== -1) {
            click(getCenterPoint(texts[i].location).x,getCenterPoint(texts[i].location).y)
            return true;
        }
    }
    sleep(200);
    texts = ocrText();
    for (var i = 0; i < texts.length; i++) {
        if (texts[i].words.indexOf(t) !== -1) {
            click(getCenterPoint(texts[i].location).x,getCenterPoint(texts[i].location).y)
            return true;
        }
    }
    return false;
}


//添加运行悬浮窗
function addRunFloatWindow() {
    var win = floaty.rawWindow(
        <vertical h="10" bg="#ff0000" w="10" alpha="0.4">
            <text
                id="log"
                line="5"
                textColor="white"
                textSize="14sp"
                typeface="normal"
            ></text>
        </vertical>
    );
    //悬浮穿透
    win.setTouchable(false);
    //悬浮移动
    win.setPosition(x - 25, 15);
}

//时间戳转日期
function timestampToDateString(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份从0开始，所以需要+1
    const day = ("0" + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
}

//控件点击
function clicktrue(ctrue) {
    var fuk = 1;
    while (true) {
        if (ctrue == null) {
            return false;
        }
        if (ctrue.clickable() == true) {
            break;
        } else {
            ctrue = ctrue.parent();
        }
        if (fuk > 6) {
            return false;
        }
        fuk++;
    }
    if (ctrue != null) {
        ctrue.click();
        return true;
    } else {
        return false;
    }
}

//计算中心点
function getCenterPoint(location) {
    var x = parseInt((location[0][0]+ location[1][0]) / 2);
    var y = parseInt((location[0][1] + location[3][1]) / 2);
    return { x: x, y: y };
}

//获取悬浮窗和录屏权限
function getScreenCapture() {
    try {
        if (isInit) {
            return;
        }
        let Thread = threads.start(function () {
            if (!floaty.checkPermission()) {
                // 没有悬浮窗权限，提示用户并跳转请求
                toast(
                    "本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。"
                );
                floaty.requestPermission();
                // exit();
            } else {
                //由于系统间同意授权的文本不同，采用正则表达式
            }
            let Allow = textMatches(/(允许|立即开始|统一)/).findOne(10 * 1000);
            if (Allow) {
                Allow.click();
            }
        });
        if (!requestScreenCapture(false)) {
            toastLog("请求录屏权限失败");
            return false;
        } else {
            Thread.interrupt();
            return true;
        }
    } catch (e) {
        log(e)
    }
}


//等待文本出现
function containstextWait(t, timeout) {
    if (!timeout) {
        timeout = 3000;
    }
    let startTime = new Date().getTime();
    while (true) {
        if (new Date().getTime() - startTime > timeout) {
            log(`等待${t}超时`);
            return false;
        }
        if (textContains(t).exists()) {
            sleep(100);
            return true;
        } else {
            sleep(100);
        }
    }
}

//点击一个文本
function clickTextCenter(t, timeout) {
    if (!timeout) {
        timeout = 5000;
    }
    let startTime = new Date().getTime();
    while (true) {
        try {
            if (new Date().getTime() - startTime > timeout) {
                log(`点击${t}超时1`);
                return false;
            }
            // log(`检查${t}元素`);
            let btn = text(t).findOnce();
            if (btn) {
                btn.clickCenter();
                sleep(200);
                return true;
            } else {
                sleep(200);
            }
        } catch (e) {
            return false;
        }
    }
}

//点击一个描述
function clickDescCenter(t, timeout) {
    if (!timeout) {
        timeout = 6000;
    }
    let startTime = new Date().getTime();
    while (true) {
        if (new Date().getTime() - startTime > timeout) {
            log(`等待${t}超时2`);
            return false;
        }
        let node = desc(t).findOnce()
        if (node) {
            try {
                node.click()
                sleep(200);
                return true;
            } catch (e) {
                return false;
            }
        } else {
            sleep(200);
        }
    }
}

//点击一个文本开头
function clickTextsStarts(t, timeout) {
    if (!timeout) {
        timeout = 6000;
    }
    let startTime = new Date().getTime();
    while (true) {
        try {
            if (new Date().getTime() - startTime > timeout) {
                log(`等待${t}超时3`);
                return false;
            }
            let node = textStartsWith(t).findOnce()
            if (node) {
                node.clickCenter();
                sleep(200);
                return true;
            } else {
                sleep(200);
            }
        } catch (e) {
            return false;
        }
    }
}

//获取剪贴板内容
function myGetClip() {
    //获取剪贴板内容
    var clip = null;
    threads.start(function () {
        var win = floaty.window(
            <vertical>
                <input id="input" w="*" h="50" />
            </vertical>
        );
        ui.run(() => {
            win.requestFocus();
            win.input.requestFocus();
        });
        et = className("EditText").findOne();
        et.paste();
        clip = win.input.text();
        // log("剪贴板内容：" + clip);
        ui.run(() => {
            win.close();
        });
    });
    let startTime = new Date().getTime();
    while (true) {
        if (new Date().getTime() - startTime > 5000) {
            log(`获取剪贴板内容超时`);
            return false;
        }
        if (clip) {
            break;
        }
        sleep(100);
    }
    return clip;
}
//获取三天前的时间
function getThreeDaysAgo() {
    let date = new Date();
    date.setDate(date.getDate() - 3);
    return date.getTime();
}

//关闭弹窗
function closePopup() {
    let node = indexInParent("100").drawingOrder("1").depth("2").clickable(true).findOnce();
    if (node) {
        toastLog("关闭弹窗1");
        node.clickCenter();
        return true;
    }
    node = indexInParent("163").drawingOrder("1").depth("2").clickable(true).findOnce();
    if (node) {
        toastLog("关闭弹窗2");
        node.clickCenter();
        return true;
    }
    node = text("访问地理位置信息权限说明").findOnce();
    if (node) {
        toastLog("关闭弹窗3");
        node = text("取消").findOnce();
        if (node) {
            node.clickCenter();
        }
        return true;
    }
}

//格式化时间
function timesToDate(timestamp) {
    var date = new Date(timestamp);
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString().padStart(2, "0");
    var day = date.getDate().toString().padStart(2, "0");
    var hour = date.getHours().toString().padStart(2, "0");
    var minute = date.getMinutes().toString().padStart(2, "0");
    var second = date.getSeconds().toString().padStart(2, "0");
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
var toolboxTools = {
    clicktrue,
    addRunFloatWindow,
    timestampToDateString,
    getScreenCapture,
    timesToDate,
    clickTextCenter,
    clickDescCenter,
    myGetClip,
    getThreeDaysAgo,
    clickTextByOcr,
    clickTextsStarts,
    hasText,
    hasTextStart,
    waitTextByOcr,
    clickHasTextByOcr,
    ocrText,
    containstextWait,
    closePopup,
    getCenterPoint,
    init
};

function test() {
    getScreenCapture()
    sleep(2000)
}
// test()
module.exports = toolboxTools;
